import functools
import json

from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for,jsonify,Response,abort
)
from werkzeug.security import check_password_hash, generate_password_hash

from flaskr.db import get_db

from flask_cors import *

bp = Blueprint('user', __name__, url_prefix='/')

cors=CORS(bp,supports_credentials=True)

@bp.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        #fetch data from request
        # data = request.args
        data = request.get_data()    
        data = json.loads(data.decode("utf-8"))  
        username = data['username']
        password = data['password']
        permission = data['permission']
        #search data from datebase
        if permission == 'Medical_point': 
            db = get_db()
            user = db.execute(
                'SELECT id,username,password FROM Medical_point WHERE username = ?', (username,)
            ).fetchone()
        elif permission == 'User': 
            db = get_db()
            user = db.execute(
                'SELECT id,username,password FROM User WHERE username = ?', (username,)
            ).fetchone()
        elif permission == 'Root': 
            db = get_db()
            user = db.execute(
                'SELECT id,username,password FROM Root WHERE username = ?', (username,)
            ).fetchone()
        else:
            user = None
        #check information
        if user is None:
            res = Response('用户名或密码错误')
            abort(res)
        elif not check_password_hash(user['password'], password):
            res = Response('用户名或密码错误')
            abort(res)
        #set session
        session.clear()
        session["id"] = user['id']
        session["permission"] = permission
        session.permanent = True #set session time

        return jsonify({'user_id':session.get('id'),'permission':session.get('permission')})
    abort(405)  #method not allowed

@bp.route('/register', methods=['POST'])
def register():
    if request.method == 'POST':
        #fetch data from request
        data = request.get_data()    
        data = json.loads(data.decode("utf-8"))  
        username = data['username']
        password = data['password']
        phone = data['phone']
        #check username not be used
        db = get_db()
        user = db.execute(
            'SELECT username FROM user WHERE username = ?', (username,)
            ).fetchone()
        if user is not None:
            res = Response(f"用户名 {username} 已被注册")
            abort(res)
        #insert record into database,error will occur if phone number is used
        try:
            db.execute(
                "INSERT INTO user (username, password, phone, status) VALUES (?, ?, ?, 0)",
                (username, generate_password_hash(password), phone,),
            )
            db.commit()
        except db.IntegrityError:
            res = Response(f"手机号 {phone} 已被注册")
            abort(res)
        else:
            user = db.execute(
                'SELECT id FROM user WHERE username = ?', (username,)
            ).fetchone()
            errormsg = '注册成功'
            #set session
            session.clear()
            session["id"] = user['id']
            session["permission"] = 'user'
            session.permanent = True
            return jsonify({'user_id':session.get('id'),'permission':session.get('permission')})
    abort(405)  #method not allowed